package com.ipay.wechat.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.CDATA;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

import com.ipay.utils.StringUtil;
import com.ipay.wechat.core.WechatParam;


public class XmlUtil {
	
	private static Logger logger = LoggerFactory.getLogger(XmlUtil.class);
	
	public static HashMap<String, String> parse(String postStr) {
		HashMap<String, String> map = new HashMap<String, String>();
		StringReader sr = null;
		try {
			sr = new StringReader(postStr);
			InputSource is = new InputSource(sr);
			Document doc = (new SAXBuilder()).build(is);
			Element root  = doc.getRootElement();
			List<Element> list = root.getChildren();
			for (Element ele : list) {
				map.put(ele.getName(), ele.getTextTrim());
			}
		} catch (Exception e) {
			logger.error("xml解包出错，错误信息：", e);
		}finally {
			if(sr!=null) {
				sr.close();
			}
		}
		return map;
	}
	
	public static String pack(WechatParam param) {
		Document doc = new Document();
		Element xml = new Element("xml");
		doc.setRootElement(xml);

		Iterator<Map.Entry<String, String>> it = param.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry<String,String> m = it.next();
			String key = m.getKey();
			String value = m.getValue();
			if(StringUtil.isEmpty(key)){ continue;}
			Element item = new Element(key);
			item.addContent(new CDATA(value));
			xml.addContent(item);
		}
		/*for(String key : param.keySet()) {
			if(StringUtil.isEmpty(key)){ continue;}
			Element item = new Element(key);
			item.addContent(new CDATA(param.get(key)));
			xml.addContent(item);
		}*/
		XMLOutputter xmlout = new XMLOutputter(); 
		ByteArrayOutputStream bo = null;     
        try {
        	bo = new ByteArrayOutputStream();
			xmlout.output(doc, bo);
			String s = bo.toString("UTF-8");
			return s;
		} catch (Exception e) {
			logger.error("组包出错：", e);
			return null;
		}finally {
			try {
				if(bo != null) {
					bo.close();
				}
			} catch (IOException e) {
				logger.info("流关闭失败："+ e.getMessage());
			}
		}
	}
	
	public static void main(String[] args) {
		String str = "<xml>" + "<ToUserName><![CDATA[toUser]]></ToUserName>"
				+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
				+ "<CreateTime>1348831860</CreateTime>"
				+ "<MsgType><![CDATA[text]]></MsgType>"
				+ "<Content><![CDATA[this is a test]]></Content>"
				+ "<MsgId>1234567890123456</MsgId>" + "</xml>";
		Map<String,String> map = parse(str);
		System.out.println(map);
	}
}
